import EventBus from '@/plugins/EventBus'
import { onMounted, onBeforeUnmount } from 'vue'

export function useBus() {
  /**
   * @param {Array} events 订阅的事件数组
   * @param {Boolean} immediate 是否立即执行订阅
   */
  const on = (events, immediate = true) => {
    if (events && events.length) {
      const handler = () => events.forEach((item) => EventBus.on(...item))

      if (immediate) {
        handler()
      } else {
        onMounted(handler)
      }

      onBeforeUnmount(() => events.forEach((item) => EventBus.off(...item)))
    }
  }

  return {
    on,
    emit: EventBus.emit
  }
}
